.TH std::identity 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::identity \- std::identity

.SH Synopsis
   Defined in header <functional>
   struct identity;                \fI(since C++20)\fP

   std::identity is a function object type whose operator() returns its argument
   unchanged.

.SH Member functions

   operator() returns the argument unchanged
              \fI(public member function)\fP

std::identity::operator()

   template< class T >
   constexpr T&& operator()( T&& t ) const noexcept;

   Returns std::forward<T>(t).

.SH Parameters

   t - argument to return

.SH Return value

   std::forward<T>(t).

.SH Notes

   std::identity serves as the default projection in constrained algorithms. Its direct
   usage is usually not needed.

.SH Example


// Run this code

 #include <algorithm>
 #include <functional>
 #include <iostream>
 #include <ranges>
 #include <string>

 struct Pair
 {
     int n;
     std::string s;
     friend std::ostream& operator<<(std::ostream& os, const Pair& p)
     {
         return os << '{' << p.n << ", " << p.s << '}';
     }
 };

 // A range-printer that can print projected (modified) elements of a range.
 template<std::ranges::input_range R,
          typename Projection = std::identity> //<- Notice the default projection
 void print(std::string_view const rem, R&& range, Projection projection = {})
 {
     std::cout << rem << '{';
     std::ranges::for_each(
         range,
         [O = 0](const auto& o) mutable { std::cout << (O++ ? ", " : "") << o; },
         projection
     );
     std::cout << "}\\n";
 }

 int main()
 {
     const auto v = {Pair{1, "one"}, {2, "two"}, {3, "three"}};

     print("Print using std::identity as a projection: ", v);
     print("Project the Pair::n: ", v, &Pair::n);
     print("Project the Pair::s: ", v, &Pair::s);
     print("Print using custom closure as a projection: ", v,
         [](Pair const& p) { return std::to_string(p.n) + ':' + p.s; });
 }

.SH Output:

 Print using std::identity as a projection: {{1, one}, {2, two}, {3, three}}
 Project the Pair::n: {1, 2, 3}
 Project the Pair::s: {one, two, three}
 Print using custom closure as a projection: {1:one, 2:two, 3:three}

.SH See also

   type_identity returns the type argument unchanged
   (C++20)       \fI(class template)\fP
